<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm1" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="知识编号" prop="knowleNum">
        <el-input
          v-model="queryParams.knowleNum"
          placeholder="请输入知识编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="内容" prop="contents">
        <el-input
          v-model="queryParams.contents"
          placeholder="请输入内容"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="claifica">
        <treeselect v-model="queryParams.claifica"
                    :options="claificaOptions"
                    :normalizer="normalizer"
                    placeholder="选择类型"
                    style="width: 220px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">

        <el-badge :value="stagTotal" class="item">
        <el-popover
          placement="right"
          width="666"
          trigger="click">
          <el-table :data="stagList">
            <el-table-column width="160"
            property="knowleNum" label="知识编号">
            </el-table-column>
            <el-table-column width="160"
             property="title" label="标题"
             align="center"></el-table-column>
            <el-table-column width="160"
             property="addTime" label="暂存时间"
             align="center"></el-table-column>
            <el-table-column width="160"
             property="address" label="操作"
             align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click="handleView(scope.row)">
                  继续编辑
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDel(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="stagTotal>0"
            :total="stagTotal"
            :page.sync="stagParams.pageNum"
            :limit.sync="stagParams.pageSize"
            :pageSizes="[stagParams.pageSize]"
            @pagination="getStagList"
          />
            <el-button
              type="primary"
              plain
              icon="el-icon-cloudy"
              size="mini"
              slot="reference"
              @click=""
            >暂存</el-button>
        </el-popover>
        </el-badge>


      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table
      :data="knowleBaseList"
      border
      stripe
      style="width: 100%">
      <el-table-column
        prop="index"
        label="序号"
        type="index">
      </el-table-column>
      <el-table-column
        prop="knowleNum"
        label="知识编号">
      </el-table-column>
      <el-table-column
        prop="claificaName"
        label="分类名称"
        align="center">
      </el-table-column>
      <el-table-column
        prop="title"
        label="标题"
        align="center">
      </el-table-column>
      <el-table-column
        prop="delFlag"
        label="状态"
        align="center">
        <template slot-scope="scope">
          <span>{{scope.row.delFlag === "1" ?"未发布":'发布'}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="userName"
        label="添加人"
        align="center">
      </el-table-column>
      <el-table-column
        prop="userName"
        label="是否公开"
        align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.openStatus"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            active-text="公开"
            inactive-text="不公开"
            @change="doUpdateOpenStatus(scope.row)"
            inactive-color="#ff4949">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="version"
        :formatter="verFormat"
        label="版本号"
        align="center">
      </el-table-column>
      <el-table-column
        prop="updateTime"
        label="最新发布日期"
        align="center">
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="viewContent(scope.row)">
            查看内容
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)">
            修改
          </el-button>
          <!--<el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="historVers(scope.row)">
            查看历史版本
          </el-button>-->

          <el-dropdown size="mini" trigger="click"  @command="(command) => handleCommand(command, scope.row)">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-d-arrow-right">
              更多
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="del" icon="el-icon-delete">删除</el-dropdown-item>
              <el-dropdown-item command="viewHistorVer" icon="el-icon-view">查看历史版本</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!--修改-->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="50%"
      :close-on-click-modal="false"
      :before-close="handleClose"
      append-to-body>
      <el-form :inline="true" ref="form" :model="form" :rules="rules">
        <el-form-item label="标题"  prop="title">
          <el-input v-model="form.title" :disabled="disRecord" style="width:500px" placeholder="标题"></el-input>
        </el-form-item>
        <el-form-item label="分类"  prop="claifica">
            <treeselect v-model="form.claifica"
                        :options="claificaOptions"
                        :normalizer="normalizer"
                        placeholder="选择类型"
                        style="width: 220px;" />
        </el-form-item>
        <el-form-item label="内容" prop="contents">
          <editor v-model="form.contents" :min-height="540"/>
        </el-form-item>
        <el-form-item  v-if="disRecord" label="更新日志" prop="updateRecords">
          <el-input
            type="textarea"
            style="min-width:540px;"
            :autosize="{ minRows: 5}"
            placeholder="请输入更新日志"
            v-model="form.updateRecords">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="stagForm">暂 存</el-button>
        <el-button type="primary" @click="submitForm">发 布</el-button>
      </span>
    </el-dialog>
    <!--添加-->
    <el-dialog
      :title="title"
      :visible.sync="openAdd"
      width="50%"
      :close-on-click-modal="false"
      :before-close="addhandleClose"
      append-to-body>
      <el-form :inline="true" ref="addform" :model="addform" :rules="rules">
        <el-form-item label="标题"  prop="title">
          <el-input v-model="addform.title" :disabled="disRecord" style="width:500px" placeholder="标题"></el-input>
        </el-form-item>
        <el-form-item label="分类"  prop="claifica">
          <treeselect v-model="addform.claifica"
                      :options="claificaOptions"
                      :disabled="disRecord"
                      :normalizer="normalizer"
                      placeholder="选择类型"
                      style="width: 220px;" />
        </el-form-item>
        <el-form-item label="内容" prop="contents">
          <editor v-model="addform.contents" :min-height="540"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addcancel">取 消</el-button>
        <el-button type="primary" @click="addForm(1)">暂 存</el-button>
        <el-button type="primary" @click="addForm(2)">发 布</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  listKnowBase,
  getKnowBase,
  addKnowLeBase,
  editKnowLeBase,
  editDelKnowLeBase,
  delKnowLeBase,
  updateOpenStatus
} from '@/api/knowledge/knowBase'
import {updateContent} from "@/api/knowledge/content";
import {getClaificaTree,listClaifica} from "@/api/knowledge/claifica";
import {addStag,getList,getStag,delStag,updateStag,getExist} from "@/api/knowledge/staging";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name:"KnowleBase",
  components: {
    Treeselect
  },
  data(){
    const validConten=(rule,value,callback)=>{
      value=this.getText(value);
      value.trim().length==0?callback(new Error("知识内容不能为空")):callback();
    }
    return {
      queryParams:{
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'kb.knowle_num',
        isAsc: 'desc',
        title: null,
        content: null,
        claifica:null,
        knowleNum:null,
        dept:null
      },
      stagParams:{
        pageNum: 1,
        pageSize: 10,
        /*orderByColumn: 'kb.knowle_num',*/
        isAsc: 'desc',
      },
      //暂存
      stagTotal:0,
      knowleBaseList:[],
      stagList:[],
      versionList: [],
      // 显示搜索条件
      showSearch: true,
      openAdd:false,
      open:false,
      openver:false,
      //对话窗标题
      title:'',
      form:{},
      addform:{},
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        claifica: [
          { required: true, message: '请选择知识类型', trigger: 'blur' }
        ],
        contents: [
          { required: true, message: '知识内容不能为空', trigger: 'blur' },
          { validator: validConten, trigger: 'blur'}
        ],
        updateRecords: [
          { required: true, message: '更新日志不能为空', trigger: 'blur' }
        ]
      },
      claificaOptions:[],
      // 知识库分类表格数据
      claificaList: [],
      //更新显示日志
      // disRecord:false,
      disRecord:true,
      // 总条数
      total: 0,
    }
    },
  created(){
    this.getList();
    this.getTree();
    this.getStagList();
  },
  methods: {
    doUpdateOpenStatus(val){
      updateOpenStatus(val.id).then(res => {
        this.$message.success(res.msg)
        this.getList()
      })
    },
    verFormat(row, column){
      return row.version===0?"初始版本":row.version
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm1");
      this.handleQuery();
    },
    getList(){
      listKnowBase(this.queryParams).then(resoponse=>{
        this.knowleBaseList=resoponse.rows;
        this.total=resoponse.total;
      });
    },
    getStagList(){
      getList(this.stagParams).then(resoponse=>{
        this.stagList=resoponse.rows;
        this.stagTotal=resoponse.total;
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.disRecord=false;
      this.openAdd = true;
      this.title = "添加知识库内容";
    },
    cancel(){
      this.open=false;
      // this.disRecord=false;
      this.reset();
    },
    addcancel(){
      this.openAdd=false;
      // this.disRecord=false;
      this.addReset();
    },
    addReset(){
      this.form={
        id:null,
        /*标题*/
        title:null,
        /*内容*/
        content:"",
        /*分类*/
        claifica:null,
        /*更新日志*/
        updateRecords:null,
        contentId:null,
        delFlag:null
      };
      this.resetForm("addform");
    },
    reset(){
      this.form={
        id:null,
        /*标题*/
        title:null,
        /*内容*/
        content:"",
        /*分类*/
        claifica:null,
        /*更新日志*/
        updateRecords:null,
        contentId:null,
        delFlag:null
      };
      this.resetForm("form");
    },
    submitForm(){
      this.rules.updateRecords=[
        { required: true, message: '更新日志不能为空', trigger: 'blur' }
      ]
      this.$refs["form"].validate(valid => {
        if(valid){
          if(this.form.id!=null){
            this.form.delFlag="2"
            editKnowLeBase(this.form).then(response=>{
              this.$modal.msgSuccess("操作成功");
              this.getStagList();
              this.getList();
            });
          }else{
            addKnowLeBase(this.form).then(response=>{
              this.$modal.msgSuccess("新增成功");
              this.getStagList();
              this.getList();
            });
          }
          this.open=false;
          // this.disRecord=false;

        }
      });

    },
    stagForm(){
      this.rules.updateRecords=[]
      this.$refs["form"].validate(async valid => {
        if(valid){
          if(this.form.sid!=null){
            updateStag(this.form).then(res=>{
              this.$modal.msgSuccess("操作成功");
              this.getStagList()
            })
          }else{
            //判断是否存在
            let exist = await getExist(this.form.id).then(resopnse=>{
              return resopnse.data;
            })
            if(exist){
              this.$modal.msgSuccess("已有暂存，请在最新版本修改");
              return
            }

            if(this.form.delFlag==="1"){
              this.form.id=this.form.contentId
              await updateContent(this.form).then(response=>{
                this.$modal.msgSuccess("操作成功");
              })
            }else{
              await addStag(this.form).then(response=>{
                this.$modal.msgSuccess("操作成功");
              })
            }
            await this.getStagList()
          }
          this.getList();
          this.open=false;
        }
      })
    },
    addForm(state){
      this.$refs["addform"].validate(valid => {
        if(valid){
          this.addform.delFlag=state
            addKnowLeBase(this.addform).then(response=>{
              this.$modal.msgSuccess("新增成功");
              this.getList();
            });
          this.openAdd=false;
          // this.disRecord=false;
          this.getStagList()
        }
      });
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children
      };
    },
    getTree(){
      /*listClaifica().then(response => {

        this.claificaList = this.handleTree(response.data,"id","parendId");
        console.log(this.claificaList)
      });*/

      getClaificaTree().then(response=>{
         this.claificaOptions=response.data;
      })
    },
    viewContent(row){
      const params = { id:row.contentId };
      this.$tab.openPage("知识内容", "/knowledge/knowlebase/content",params);
    },

    handleUpdate(row){
      this.reset();

      if(row.delFlag==='1'){
        this.disRecord=false;
      }
      getKnowBase(row.id).then(response=>{
        this.form = response.data;
        this.form.contentId=row.contentId;
        this.form.delFlag=row.delFlag;
        this.open = true;
        this.title = "修改知识库内容";
      })

    },
    //暂存查看
    handleView(row){
      this.reset();
      getStag(row.sid).then(response=>{
        this.form = response.data;
        this.open = true;
        this.title = "修改知识库内容";
      })

    },
    //暂存删除
    handleDel(row){
      delStag(row.sid).then(response=>{
        this.$modal.msgSuccess("删除成功");
        this.getStagList();
      })
    },
    handleClose(done){
      this.disRecord=true;
      done();
    },
    addhandleClose(done){
      this.disRecord=true;
      this.addReset();
      done();
    },
    historVers(row){
      const params = { id:row.id };
      this.$tab.openPage("历史版本", "/knowledge/knowlebase/historVers",params);
      /*this.openver=true;
      getVersion(row.id).then(response => {
        this.versionList = response.data;
      })*/
    },
    delKnow(row){
      editDelKnowLeBase(row.id).then(response=>{
        this.$modal.msgSuccess("删除成功");
        this.getList();
      })
    },
    handleCommand(command,row){
      switch (command) {
        case "viewHistorVer":
          this.historVers(row);
          break;
        case "del":
          this.delKnow(row);
          break;
        default:
          break;
      }
    },
    getText(str) {
      return str
        .replace(/<[^<p>]+>/g, '')  // 将所有<p>标签 replace ''
        .replace(/<[</p>$]+>/g, '')  // 将所有</p>标签 replace ''
        .replace(/&nbsp;/gi, '')  // 将所有 空格 replace ''
        .replace(/<[^<br/>]+>/g, '') // 将所有 换行符 replace ''
    }
  }


}
</script>

